import json
import re
from django import http
from django.contrib.auth import login, logout, authenticate
from django.db import DatabaseError
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views.generic.base import View
from .models import Users
from mgproject.utils.exceptions import Forbbiden

class EmailView(View):
    def post(self,request):
        '''
        保存当前用户邮箱地址
        :param request:
        :return:
        '''
        # 接受参数(Json格式)
        params = request.body.decode() # 将字节转换为字符

        # 校验参数
        if params is None:
            return JsonResponse({'code':4001,'errormsg':'缺少参数'})

        dict_params = json.loads(params)  # 转为字典类型
        count = Users.objects.filter(id=dict_params['userid']).update(email=dict_params['email'])

        # 响应结果
        if count>0:
            return JsonResponse({'code':200,'errormsg':'ok'})
        return JsonResponse({'code':500,'errormsg':'保存邮箱失败！'})


class UserCenterView(View):
    def get(self,request):
        '''
        显示用户中心页面
        :param request:
        :return:
        '''

        return render(request, 'userapp/user_center.html')

        #  判断当前访客是否登录
        # if request.user.is_authenticated:
        #     return render(request,'userapp/user_center.html')
        # else:
        #     return redirect(reverse('newsapp:indexes'))


class LoginView(View):
    def get(self,request):
        '''
        用户名登录视图
        :return:
        '''
        next = request.GET.get('next','')
        return render(request,'userapp/login.html',{'next':next})

    def post(self,request):
        '''
        处理登录请求
        :param request:
        :return:
        '''
        # 接收参数
        username = request.POST.get('username','')
        password = request.POST.get('password','')
        remember = request.POST.get('remember','')
        next = request.POST.get('next','')

        # 校验参数
        if not all([username,password]):
            # return http.HttpResponseForbidden('缺少必传参数！')
            raise Forbbiden('请填写账号密码！')

        # # 判断用户名是否是5-8个字符
        # if not re.match(r'^[a-zA-Z][a-zA-Z0-9_]{4,7}$', username):
        #     # return http.HttpResponseForbidden('请输入5-8个字符串的用户名！')
        #     raise Forbbiden('请输入5-8个字符串的用户名！')
        # 判断密码是否是3-8位字符
        # if not re.match(r'^[a-zA-Z0-9]{3,8}$', password):
        #     # return http.HttpResponseForbidden('请输入3-8位的密码！')
        #     raise Forbbiden('请输入3-8位的密码！')

        # 认证参数是否正确
        user = authenticate(username=username,password=password)
        if user is None:
            return render(request,'userapp/login.html',{'login_error_msg':'用户名或密码错误'})

        # 状态保持
        login(request,user)
        '''对记住我时效性进行处理'''
        if remember != 'on':
            request.session.set_expiry(0)  # 设置有效时间 浏览器关闭就过期
        else:
            request.session.set_expiry(None)  # 默认两周

        if next:
            return redirect(next)

        # 响应结果
        return redirect(reverse('newsapp:indexes'))  # 正常就重定向到新闻首页


class RegisterFView(View):
    '''
    用户注册校验
    '''

    def get(self,request):
        return render(request,'userapp/register.html')

    def post(self,request):
        '''
        表单校验
        '''
        username = request.POST.get('username','')  # 获取username 没得到返回空
        password = request.POST.get('password', '')
        phone = request.POST.get('phone', '')

        # 校验参数 （完整参数校验，格式校验）
        # 判断参数是否齐全
        if not all([username,password,phone]):
            raise Forbbiden('缺少必传参数')
        # 判断用户名是否是5-8个字符
        if not re.match(r'^[a-zA-Z][a-zA-Z0-9_]{4,7}$',username):
            raise Forbbiden('请输入5-8个字符串的用户名！')
        # 判断密码是否是3-8位字符
        if not re.match(r'^[a-zA-Z0-9]{3,8}$',password):
            raise Forbbiden('请输入3-8位的密码！')
        # 判断手机号是否合法
        if not re.match(r'^1[3,5,7,8,9]\d{9}$',phone):
            raise Forbbiden('请输入正确手机号！')

        # 保存注册数据（入库操作）
        try:
            user = Users.objects.create_user(username=username,password=password,phone=phone)
        except DatabaseError:
            return render(request,'userapp/register.html',{'reg_error_msg':'注册失败咯！'})

        # 状态保持
        login(request,user)

        # 返回响应结果（）
        return redirect(reverse('newsapp:indexes')) # 逆向解析 newsapp为应用名，index为name名


class UsernameCount(View):
    def get(self,request,username):
        '''
        查询当前用户名的记录数
        :param request:
        :param username:
        :return:
        '''
        count = Users.objects.filter(username=username).count()
        return JsonResponse({'code':200,'errormsg':'ok','count':count})


class LogoutView(View):
    def get(self,request):
        '''
        用户退出登录
        :param request:
        :return:
        '''
        logout(request)
        return redirect(reverse('newsapp:indexes'))


class PhoneCount(View):
    def get(self,request,phone):
        '''
        查询当前手机号的记录数
        :param request:
        :param username:
        :return:
        '''
        count = Users.objects.filter(phone=phone).count()
        return JsonResponse({'code':200,'errormsg':'ok','count':count})
